package tcc.ctrl;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import tcc.dao.UsuarioDAO;
import tcc.model.Usuario;
import tcc.util.MD5;

@WebServlet(urlPatterns = { "/cadastro" })
public class CadastroCtrl extends HttpServlet {
	private static final long serialVersionUID = 7110613356372806903L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		req.setAttribute("content", "cadastro.jsp");
		req.setAttribute("usuario", req.getSession().getAttribute("usuario"));
		req.getRequestDispatcher("/template.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		Map<String, String[]> params = req.getParameterMap();

		UsuarioDAO usuarioDAO = new UsuarioDAO();

		Usuario uVerificacao = usuarioDAO
				.recuperarPorEmail(params.get("email")[0]);

		if (uVerificacao != null) {
			resp.sendRedirect("./cadastro?erro=emailexiste");
			return;
		}

		Usuario u = new Usuario();
		u.setNome(params.get("nome")[0]);
		u.setEmail(params.get("email")[0]);
		u.setSenhaMD5(MD5.passwd2MD5(params.get("password")[0]));

		usuarioDAO.salvar(u);
		req.getSession().setAttribute("usuario", u);
		resp.sendRedirect("./");
	}
}
